#!/usr/bin/env python3
"""
ADAM Model Demo Program

This program demonstrates how to use the ADAM (Advanced Dissolution, Absorption, and Metabolism) model
based on Excel parameters for detailed drug absorption analysis.

Author: BlackCat@CPPO
Version: 2.0.0
"""

import os
import sys
import numpy as np
import matplotlib.pyplot as plt

# Add project root to path
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

from src.absorption.absorption_module import AbsorptionModel
from src.absorption.adam_model import ADAMModel
from src.visualization.plot_generator import PlotGenerator

def demo_adam_model():
    """Demonstrate ADAM model functionality"""
    
    print("=== ADAM Model Demo ===")
    
    # Sample drug parameters
    drug_params = {
        'dose': 100,  # mg
        'solubility': 0.8,  # mg/mL
        'permeability': 2e-4,  # cm/s
        'molecular_weight': 325.4,  # g/mol
        'pKa': 7.8,
        'logP': 2.5,
        'particle_size': 50,  # μm
        'density': 1.2,  # g/cm³
        'use_adam': True
    }
    
    # Create absorption model (ADAM enabled)
    absorption_model = AbsorptionModel(drug_params)
    
    # Create ADAM model directly
    adam_model = ADAMModel(drug_params)
    
    # Time settings
    time_points = np.linspace(0, 24, 100)
    
    # Calculate BCS classification
    print("\n1. BCS Classification Analysis")
    bcs_result = absorption_model.calculate_bcs_classification(
        drug_params['solubility'],
        drug_params['permeability'],
        drug_params['dose']
    )
    print(f"BCS Class: {bcs_result['class']}")
    print(f"High Solubility: {bcs_result['high_solubility']}")
    print(f"High Permeability: {bcs_result['high_permeability']}")
    print(f"Dose/Solubility Ratio: {bcs_result['dose_solubility_ratio']:.2f}")
    
    # Calculate ADAM absorption
    print("\n2. ADAM Model Absorption Analysis")
    adam_result = adam_model.calculate_adam_absorption(time_points)
    print(f"Bioavailability: {adam_result['bioavailability']:.2f}")
    print(f"Final Absorption Fraction: {adam_result['fraction_absorbed'][-1]:.2f}")
    
    # Regional absorption analysis
    print("\n3. Regional Absorption Analysis")
    regional_total = {}
    for region, amounts in adam_result['regional_absorbed'].items():
        total_absorbed = np.sum(amounts) * (time_points[1] - time_points[0])
        regional_total[region] = total_absorbed
        print(f"{region}: {total_absorbed:.2f} mg")
    
    # Use absorption model calculation
    print("\n4. Integrated Absorption Model")
    absorption_result = absorption_model.calculate_absorption({}, time_points)
    print(f"Total Bioavailability: {absorption_result['bioavailability']:.2f}")
    
    # Create visualization
    visualizer = PlotGenerator()
    
    # Plot regional absorption curves
    plt.figure(figsize=(15, 10))
    
    # Subplot 1: Regional drug amounts
    plt.subplot(2, 2, 1)
    for region, amounts in adam_result['regional_amounts'].items():
        plt.plot(time_points, amounts, label=region)
    plt.xlabel('Time (hours)')
    plt.ylabel('Drug amount (mg)')
    plt.title('Regional drug amounts over time')
    plt.legend()
    plt.grid(True)
    
    # Subplot 2: Cumulative absorption
    plt.subplot(2, 2, 2)
    plt.plot(time_points, adam_result['cumulative_absorption'], 'b-', linewidth=2)
    plt.xlabel('Time (hours)')
    plt.ylabel('Cumulative absorption (mg)')
    plt.title('Cumulative drug absorption')
    plt.grid(True)
    
    # Subplot 3: Regional absorption rates
    plt.subplot(2, 2, 3)
    for region, rates in adam_result['regional_absorbed'].items():
        plt.plot(time_points, rates, label=region)
    plt.xlabel('Time (hours)')
    plt.ylabel('Absorption rate (mg/h)')
    plt.title('Regional absorption rates')
    plt.legend()
    plt.grid(True)
    
    # Subplot 4: Regional contribution pie chart
    plt.subplot(2, 2, 4)
    labels = list(regional_total.keys())
    sizes = list(regional_total.values())
    plt.pie(sizes, labels=labels, autopct='%1.1f%%')
    plt.title('Regional absorption contribution')
    
    plt.tight_layout()
    plt.show()
    
    return {
        'bcs_classification': bcs_result,
        'adam_absorption': adam_result,
        'regional_analysis': regional_total
    }

def demo_sample_integration():
    """Demonstrate sample parameter integration"""
    
    print("\n=== Sample Parameter Integration Demo ===")
    
    # Create absorption model
    absorption_model = AbsorptionModel({})
    
    # Use sample parameters for demo
    sample_params = {
        'dose': 100,
        'solubility': 14.0,
        'permeability': 1.2e-05,
        'pKa': 9.38,
        'logP': 0.46
    }
    
    # Calculate BCS classification
    bcs_integration = absorption_model.calculate_bcs_classification(
        sample_params['solubility'],
        sample_params['permeability'], 
        sample_params['dose']
    )
    print(f"BCS classification complete: {bcs_integration['class']}")
    print(f"Classification details: {bcs_integration}")
    
    return bcs_integration

def demo_food_effect():
    """Demonstrate food effect"""
    
    print("\n=== Food Effect Demo ===")
    
    # Fasted state parameters
    fasted_params = {
        'dose': 100,
        'solubility': 1.0,
        'permeability': 1e-4,
        'use_adam': True
    }
    
    # Fed state parameters
    fed_params = {
        'dose': 100,
        'solubility': 1.5,  # Food may increase solubility
        'permeability': 0.8e-4,  # Food may decrease permeability
        'use_adam': True
    }
    
    time_points = np.linspace(0, 24, 100)
    
    # Create model instances
    fasted_model = AbsorptionModel(fasted_params)
    fed_model = AbsorptionModel(fed_params)
    
    # Calculate absorption
    fasted_result = fasted_model.calculate_absorption({}, time_points)
    fed_result = fed_model.calculate_absorption({}, time_points)
    
    # Calculate food effect using trapezoid (replaced deprecated trapz)
    from scipy.integrate import trapezoid
    fasted_auc = trapezoid(fasted_result['rate'], time_points)
    fed_auc = trapezoid(fed_result['rate'], time_points)
    food_effect_ratio = fed_auc / fasted_auc
    
    print(f"Fasted AUC: {fasted_auc:.2f} mg·h/L")
    print(f"Fed AUC: {fed_auc:.2f} mg·h/L")
    print(f"Food Effect Ratio: {food_effect_ratio:.2f}")
    
    if food_effect_ratio > 1.2:
        print("Food increases absorption")
    elif food_effect_ratio < 0.8:
        print("Food decreases absorption")
    else:
        print("Food has no significant effect")

if __name__ == "__main__":
    # Run demo
    demo_adam_model()
    demo_sample_integration()
    demo_food_effect()
    
    print("\n=== ADAM Model Demo Complete ===")
    print("Generated chart saved as: adam_analysis_demo.png")